package com.test.ayi.controller;

import com.alibaba.fastjson2.JSON;
import com.test.ayi.service.EmailService;
import com.test.ayi.service.EmailServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@RestController
public class Mail {
    private static final Logger log = LoggerFactory.getLogger(Mail.class);

    @Autowired
    private EmailService emailService;

    @GetMapping("mailTest")
    public List<EmailServiceImpl.EmailContent> mailTest(@RequestParam("date")
                                                        @DateTimeFormat(pattern = "yyyy-M-d") LocalDate date) {
        log.info("start mailTest,input param:{}", date);
        List<EmailServiceImpl.EmailContent> emailContents = new ArrayList<>();
        try {
            emailContents = emailService.receiveWithImap(date);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("end mailTest,response:{}", JSON.toJSONString(emailContents));
        return emailContents;
    }

}
